package ru.amse.jsynchro.net.stream;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutput;

public class ProtocolInputStream extends LimitedInputStream {
    private ObjectOutput objectOut;
    
    protected ProtocolInputStream(InputStream in) {
        super(in);
    }
    
    public ProtocolInputStream(InputStream in, long limit, ObjectOutput objectOut) {
        super(in, limit);
        this.limit = limit;
        bufferPos = BUFFER_SIZE;
        this.objectOut = objectOut; 
    }
    
    public int read() throws IOException {
        if (limit > 0) {
            if (bufferPos == BUFFER_SIZE) {
                if (limit < BUFFER_SIZE) {
//                    System.out.println("read " + limit);
                    buffer = new byte[(int) limit];
//                    in.read(buffer, 0, (int) limit);
                    in.read(buffer);
                } else {
//                    System.out.println("read hole " + limit);
                    in.read(buffer);
//                    System.out.println("after read hole " + limit);
                }
                objectOut.writeObject("ok");
                bufferPos = 0;
            }
            limit--;
            if (buffer[bufferPos] < 0) {
                return buffer[bufferPos++] + 256;
            }
            return buffer[bufferPos++];
        }
        return -1;
    }

}
